import { $ctx, $prose } from '@milkdown/kit/utils';
import { Plugin, PluginKey, TextSelection } from '@milkdown/kit/prose/state';

/**
 * AI 改写插件 - 完全按照豆包图片样式
 */
export const aiRewritePlugin = (aiService) => $prose(() => {
  const key = new PluginKey('ai-rewrite');
  
  return new Plugin({
    key,
    state: {
      init() {
        return {
          selectedText: '',
          selectedRange: null,
          menuVisible: false
        };
      },
      apply(tr, prev, oldState, newState) {
        const { from, to } = newState.selection;
        const selectedText = newState.doc.textBetween(from, to);
        
        if (selectedText !== prev.selectedText) {
          return {
            ...prev,
            selectedText,
            selectedRange: selectedText ? { from, to } : null,
            menuVisible: selectedText.length > 0
          };
        }
        
        return prev;
      }
    },
    props: {
      handleDOMEvents: {
        mouseup(view, event) {
          const state = this.getState(view.state);
          if (state.selectedText && state.selectedText.length > 0) {
            setTimeout(() => {
              showAiMenu(view, event, state);
            }, 100);
          }
          return false;
        }
      }
    },
    view(editorView) {
      return {
        update(view, prevState) {
          const state = this.getState(view.state);
          if (!state.menuVisible) {
            hideAiMenu();
          }
        },
        destroy() {
          hideAiMenu();
        }
      };
    }
  });
  
  function showAiMenu(view, event, state) {
    const { selectedText, selectedRange } = state;
    if (!selectedText || selectedText.length < 3) return;
    
    const menu = createAiMenu(selectedText, selectedRange, view, aiService);
    
    const selection = window.getSelection();
    const range = selection.getRangeAt(0);
    const rect = range.getBoundingClientRect();
    
    menu.style.position = 'fixed';
    menu.style.left = `${rect.left}px`;
    menu.style.top = `${rect.bottom + 8}px`;
    menu.style.zIndex = '1000';
    
    document.body.appendChild(menu);
    
    const closeMenu = (e) => {
      if (!menu.contains(e.target)) {
        hideAiMenu();
        document.removeEventListener('click', closeMenu);
      }
    };
    
    setTimeout(() => {
      document.addEventListener('click', closeMenu);
    }, 100);
  }
  
  function hideAiMenu() {
    const existingMenu = document.querySelector('.douban-ai-rewrite');
    if (existingMenu) {
      existingMenu.remove();
    }
  }
  
  function createAiMenu(selectedText, selectedRange, view, aiService) {
    const menu = document.createElement('div');
    menu.className = 'douban-ai-rewrite';
    menu.innerHTML = `
      <div class="douban-header">
        <div class="douban-icon">✨</div>
        <div class="douban-title">需要我帮你改写吗？</div>
      </div>
      <div class="douban-subtitle">我能帮你润色、扩写、缩写、调整语气...</div>
      
      <div class="douban-input-section">
        <div class="douban-input-wrapper">
          <input class="douban-input" placeholder="输入优化文本的指令" />
          <button class="douban-send-btn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M2 21l21-9L2 3v7l15 2-15 2v7z"/>
            </svg>
          </button>
        </div>
      </div>

      <div class="douban-actions">
        <div class="douban-action" data-action="polish">
          <div class="action-icon">✏️</div>
          <span>润色</span>
        </div>
        
        <div class="douban-action" data-action="expand">
          <div class="action-icon">📄</div>
          <span>扩写</span>
        </div>
        
        <div class="douban-action" data-action="summarize">
          <div class="action-icon">📝</div>
          <span>缩写</span>
        </div>
        
        <div class="douban-action tone-action" data-action="tone">
          <div class="action-icon">💬</div>
          <span>调整语气</span>
          <div class="action-arrow">›</div>
        </div>
        
        <div class="douban-action" data-action="explain">
          <div class="action-icon">ℹ️</div>
          <span>解释这段话</span>
        </div>
      </div>

      <div class="tone-submenu" style="display: none;">
        <div class="tone-title">调整语气</div>
        <div class="tone-options">
          <div class="tone-option" data-tone="formal">正式</div>
          <div class="tone-option" data-tone="casual">轻松</div>
          <div class="tone-option" data-tone="professional">专业</div>
          <div class="tone-option" data-tone="friendly">友好</div>
        </div>
      </div>

      <div class="douban-result" style="display: none;">
        <div class="result-header">
          <span>改写结果</span>
          <div class="result-actions">
            <button class="result-btn retry">🔄 重试</button>
            <button class="result-btn accept">✅ 采用</button>
          </div>
        </div>
        <div class="result-content"></div>
      </div>

      <div class="douban-loading" style="display: none;">
        <div class="loading-dots"></div>
        <span>AI 正在思考中...</span>
      </div>
    `;
    
    // 事件处理
    const input = menu.querySelector('.douban-input');
    const sendBtn = menu.querySelector('.douban-send-btn');
    const toneAction = menu.querySelector('.tone-action');
    const toneSubmenu = menu.querySelector('.tone-submenu');
    
    // 自定义指令
    const handleCustom = async () => {
      const instruction = input.value.trim();
      if (!instruction) return;
      await handleAiAction('custom', selectedText, menu, aiService, instruction);
    };
    
    sendBtn.addEventListener('click', handleCustom);
    input.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') handleCustom();
    });
    
    // 调整语气子菜单
    toneAction.addEventListener('click', (e) => {
      e.stopPropagation();
      const isVisible = toneSubmenu.style.display !== 'none';
      toneSubmenu.style.display = isVisible ? 'none' : 'block';
    });
    
    // 所有操作处理
    menu.addEventListener('click', async (e) => {
      const action = e.target.closest('[data-action]')?.dataset.action;
      const tone = e.target.closest('[data-tone]')?.dataset.tone;
      
      if (action && action !== 'tone') {
        await handleAiAction(action, selectedText, menu, aiService);
      } else if (tone) {
        await handleAiAction('tone', selectedText, menu, aiService, tone);
        toneSubmenu.style.display = 'none';
      } else if (e.target.closest('.accept')) {
        const resultContent = menu.querySelector('.result-content').textContent;
        replaceSelectedText(view, selectedRange, resultContent);
        hideAiMenu();
      } else if (e.target.closest('.retry')) {
        const lastAction = menu.dataset.lastAction;
        const lastParam = menu.dataset.lastParam;
        if (lastAction) {
          await handleAiAction(lastAction, selectedText, menu, aiService, lastParam);
        }
      }
    });
    
    return menu;
  }
  
  async function handleAiAction(action, selectedText, menu, aiService, param = '') {
    const loading = menu.querySelector('.douban-loading');
    const result = menu.querySelector('.douban-result');
    const resultContent = menu.querySelector('.result-content');
    
    menu.dataset.lastAction = action;
    menu.dataset.lastParam = param;
    
    loading.style.display = 'flex';
    result.style.display = 'none';
    
    try {
      const response = await aiService.rewrite(selectedText, action, param);
      resultContent.textContent = response;
      loading.style.display = 'none';
      result.style.display = 'block';
    } catch (error) {
      console.error('AI 改写失败:', error);
      resultContent.textContent = '抱歉，AI 改写服务暂时不可用，请稍后再试。';
      loading.style.display = 'none';
      result.style.display = 'block';
    }
  }
  
  function replaceSelectedText(view, range, newText) {
    const { from, to } = range;
    const tr = view.state.tr.replaceWith(from, to, view.state.schema.text(newText));
    view.dispatch(tr);
  }
});

export class AiRewriteService {
  constructor(apiConfig = {}) {
    this.apiUrl = apiConfig.apiUrl || '/api/ai/rewrite';
    this.apiKey = apiConfig.apiKey || '';
  }
  
  async rewrite(text, action, param = '') {
    return this.simulateAiRewrite(text, action, param);
  }
  
  async simulateAiRewrite(text, action, param = '') {
    await new Promise(resolve => setTimeout(resolve, 1500 + Math.random() * 1000));
    
    const rewriteMap = {
      polish: (text) => `【润色版】${text}。这段内容经过了语言优化，表达更加准确流畅，逻辑更加清晰，用词更加恰当。`,
      expand: (text) => `${text}。进一步来说，这个观点可以从多个角度来理解和分析。首先，我们需要考虑其背景和上下文。其次，还要关注其实际应用和影响。最后，我们可以探讨其未来的发展趋势和潜在机会。`,
      summarize: (text) => {
        const words = text.split(/\s+/).slice(0, Math.max(3, Math.floor(text.split(/\s+/).length / 3)));
        return `【总结】${words.join(' ')}...（核心要点已提炼）`;
      },
      tone: (text, tone) => {
        const toneMap = {
          formal: `${text.replace(/很/g, '极为').replace(/好/g, '优秀')}。此观点具有重要的参考价值和实践意义。`,
          casual: `${text.replace(/因此/g, '所以').replace(/然而/g, '不过')}，你觉得呢？`,
          professional: `基于专业角度分析，${text}。这一观点在行业内具有重要的指导意义。`,
          friendly: `${text}，希望这个分享对你有帮助！如果还有什么疑问，随时可以讨论哦～`
        };
        return toneMap[tone] || text;
      },
      explain: (text) => `【解释】"${text}"的含义是：这段话主要表达了作者的核心观点和思考。从语言学角度来看，这里运用了多种修辞手法来增强表达效果。从内容层面分析，这反映了当前社会的某种现象或趋势，值得我们深入思考和讨论。`,
      custom: (text, instruction) => `【按照"${instruction}"的要求改写】${text}。根据您的具体指令，我对原文进行了相应的调整和优化。`
    };
    
    if (action === 'tone') {
      return rewriteMap.tone(text, param);
    } else if (action === 'custom') {
      return rewriteMap.custom(text, param);
    } else {
      const rewriteFunc = rewriteMap[action];
      return rewriteFunc ? rewriteFunc(text) : `【${action}】${text}`;
    }
  }
}